<template>
  <!--  委外-->
  <div class="content">
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="批次号">
          <el-input v-model="searchParam.batchNo" placeholder="批次号" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item label="报检状态">
          <!--        el-select isFinish true已报检 false未-->
          <el-select v-model="searchParam.isFinish" placeholder="请选择" clearable style="width: 200px">
            <el-option v-for="item in isFinishList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button icon="Download" type="primary" :loading="downLoading" @click="handleExport"
          >导出
          </el-button>
        </div>
      </div>
      <!-- 表格 -->
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 320px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            <!-- 下标 + 1，计算公式：当前页数 * 每页大小 + 当前行的索引 + 1 --> {{
              (pageSearch.current - 1) * pageSearch.pageSize +
              scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column prop="batchNo" label="批次号" align="center" min-width="200"/>
        <el-table-column prop="materialName" label="物料名称" align="center" min-width="200"/>
        <el-table-column prop="count" label="数量" align="center" min-width="200"/>
        <el-table-column prop="basicUnit" label="基本单位" align="center" min-width="200"/>
        <el-table-column prop="isFinish" label="报检状态" align="center" min-width="200">
          <template #default="scope">
            {{ scope.row.isFinish ? '已报检' : '未报检' }}
          </template>
        </el-table-column>
        <el-table-column prop="expireTime" label="物料过期时间" align="center" min-width="200"/>
        <el-table-column prop="storageName" label="库位名称" align="center" min-width="200"/>
        <el-table-column prop="finishTime" label="上次检测时间" align="center" min-width="200"/>
        <el-table-column prop="description" label="备注" align="center" min-width="200"/>
        <el-table-column label="操作" min-width="120" align="center" fixed="right">
          <template #default="scopes">
            <el-button type="text" size="small" icon="DocumentCopy" @click="doQuality(scopes.row)">质检
            </el-button>
            <!--            <el-button type="text" size="small" :icon="Files"-->
            <!--                       :disabled="scopes.row.activate" @click="doOutIn(scopes.row)">入库-->
            <!--            </el-button>-->
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination background v-model:current-page="pageSearch.current" v-model:page-size="pageSearch.pageSize"
                       :page-sizes="[10, 20, 50, 100, 200, 500]" layout="total, sizes, prev, pager, next"
                       :total="pageTotal"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
      </div>
    </div>


    <el-dialog v-model="showQuality" title="质检" width="800px">
      <el-form :model="formQuality" label-width="100px">
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="质检类型" prop="procedureOrderId">
              <el-select v-model="formQuality.qualityType" placeholder="请选择质检类型" clearable filterable
                         style="width: 300px" @change="qualityTypeChange">
                <el-option key="5" label="入库检" value="5"/>
                <el-option key="7" label="来料检" value="7"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检方案" prop="procedureOrderId">
              <el-select v-model="formQuality.qualityPlan" placeholder="请选择质检方案" clearable filterable
                         style="width: 300px" @change="qualityPlanChange">
                <el-option v-for="item in schemeTaskList" :key="item.id" :label="item.name"
                           :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="质检方式" prop="qualityWay">
              <el-select v-model="formQuality.qualityWay" placeholder="请选择质检方式" clearable
                         style="width: 300px" disabled>
                <el-option v-for="(item, index) of qualityWayList" :key="index" :label="item.label"
                           :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formQuality.qualityWay == 2">
            <el-form-item label="比例抽检">
              <el-input-number v-model="formQuality.proportionNumber" disabled :min="0"/>
              （%）
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="formQuality.qualityWay == 3">
            <el-form-item label="固定抽检">
              <el-input-number v-model="formQuality.qualityNumber" :step="1" step-strictly :min="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="方案说明" prop="qualityRemark" disabled>
              <el-input v-model="formQuality.qualityRemark" style="width: 718px" :rows="4" type="textarea"
                        disabled placeholder="请输入方案说明"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="showQuality = false">取消</el-button>
					<el-button type="primary" @click="handleQualitySave">保存</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import {computed, reactive, ref} from 'vue';
import type {FormInstance, FormRules} from 'element-plus';
import {ElMessage, ElMessageBox} from 'element-plus';
import axiosInstance from '@/utils/http/api';
import {Delete, Edit, Plus, Refresh, Search} from '@element-plus/icons-vue';
import axios from "axios";
import moment from "moment";

onMounted(() => {
  getList();
  getOption();
});


const pageSearch = ref({
  current: 1,
  pageSize: 10
});


const workOrderList = ref({});


const pageTotal = ref(null);//页面总数
const searchParam = ref({});//页面检索条件


// 判断质检类型
const getQualityTypeByValue = (e) => {
  let name = null;
  for (const item of qualityTypeList) {
    if (e == item.value) {
      name = item.label;
    }
  }
  return name;
};

// 质检类型
const qualityTypeList = reactive([
  {
    label: '部分送货',
    value: '1'
  },
  {
    label: '全部送货',
    value: '2'
  },
  {
    label: '未送货',
    value: '0'
  }
  // 继续添加更多检查类型...
]);


const paginatedData = ref([]);
const materiaList = ref([]);//物料表
const wareList = ref([]);//仓库
const procedureOrderList = ref([]);//工序订单
const supplierList = ref([]);
const storageAllList = ref([]);
// 供应商远端搜索
const supplierSearch = async (query: string) => {
  if (query) {
    try {
      const response = await axiosInstance.post(`/api/basedataSupplier/getPage`, {
        current: 1,
        pageSize: 20,
        name: query
      });
      supplierList.value = await response.data.records; // 假设返回的数据直接是供应商列表
    } catch (error) {
      supplierList.value = []; // 出错时清空列表
    }
  }
};
// czq
const showQuality = ref(false);
const formQuality = ref({});
const quParam = ref({});
const schemeTaskList = ref([]);

const doQuality = (row) => {
  quParam.value = row;
  formQuality.value = row
  qualityTypeChange(5)
  showQuality.value = true;
};

const qualityPlanChange = (e) => {
  let param = {};
  for (const item of schemeTaskList.value) {
    if (item.id == e) {
      param = item;
    }
  }
  let json = JSON.parse(param.qualityJson);
  formQuality.value = {...formQuality.value, ...json};
  formQuality.value.qualityJson = param.qualityJson;
  console.log(formQuality.value, 'param');
};

const formData = ref({});
const qualityTypeChange = (e) => {
  schemeTaskList.value = [];
  formQuality.value.qualityType = e
  if (e == 5) {
    axiosInstance.get('/api/basedataMaterial/' + quParam.value.materialId, {})
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          schemeTaskList.value = res.data.basedataQualitySchemeList.filter(item => item.qualityType == 5);
          if (schemeTaskList.value && schemeTaskList.value.length > 0) {
            formQuality.value.qualityPlan = schemeTaskList.value[0].id
            qualityPlanChange(schemeTaskList.value[0].id)
          }
        });
  } else {
    const param = {
      qualityType: e,
      current: 1,
      pageSize: 99999,
      materialId: quParam.value.materialId
    };
    axiosInstance.post('/api/basedataQualityScheme/getPage', param)
        .then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          schemeTaskList.value = res.data.records;
          if (res.data.records && res.data.records.length > 0) {
            formQuality.value.qualityPlan = res.data.records[0].id
            qualityPlanChange(res.data.records[0].id)
          }
        });
  }
};

const isFinishList = ref([
  {
    value: "false",
    label: "未报检"
  },
  {
    value: "true",
    label: "已报检"
  }
])

const qualityWayList = ref([{
  label: '全检',
  value: '1'
}, {
  label: '比例抽检',
  value: '2'
}, {
  label: '固定抽检',
  value: '3'
}, {
  label: '自定义抽检',
  value: '4'
}]);


const handleQualitySave = async () => {
  const param = formQuality.value;
  param.qualityJson = JSON.stringify(param);
  console.log(param, 'param');
  if (!param.qualityPlan) {
    ElMessage.error('请选择质检方案');
    return false;
  }
  param.id = null;
  param.status = false;
  param.sourceNo = '';
  param.batchNo = quParam.value.batchNo;
  let url = '/api/qualitySchemeTask/createMaterialTask';
  if (param.qualityType == 1 || param.qualityType == 2 || param.qualityType == 3 || param.qualityType == 4) {
    url = '/api/qualitySchemeTask/createWorkOrderTask';
  }
  axiosInstance.post(url, param)
      .then((res) => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        showQuality.value = false;
        getList();
      });
};

const downLoading = ref(false);
const handleExport = () => {
  downLoading.value = true;
  axios.post('/api/materialExamine/exportExcel', {
    ...searchParam.value
  }, {
    timeout: 30000, // 与 axiosInstance 的 timeout 相同
    responseType: 'blob',
    headers: {
      BearerToken: localStorage.getItem('token') || undefined // 与请求拦截器中的设置相同
    }
  })
      .then(response => {
        console.log(response);
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        link.href = url;
        const formattedDate = moment().format('YYYYMMDD');
        link.setAttribute('download', '二次报检' + formattedDate + '.xlsx'); // 导出的格式一定要和接口返回的文件一致
        document.body.appendChild(link);
        link.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
      })
      .finally(() => {
        downLoading.value = false;
      });
};

const getOption = () => {
  axiosInstance.post('/api/outsourcingPlan/querySourcingPlanProcedureOrder', {})
      .then(res => {
        workOrderList.value = res.data;
      });

  // 查询所有库位
  axiosInstance.post('/api/basedataStorage/getAll', {})
      .then(res => {
        storageAllList.value = res.data;
      });


  axiosInstance.post(`/api/basedataSupplier/getPage`, {
    current: 1,
    pageSize: 20
  }).then(res => {
    if (res.code == 200) {
      supplierList.value = res.data.records;
    }
  });


  axiosInstance.post('/api/planProcedureOrder/getAll', {})
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        const list = res.data;
        const loop = [];
        for (const item of list) {
          loop.push(
              {
                value: item.id,
                label: item.materialName
              }
          );
        }
        procedureOrderList.value = list;
      });

  axiosInstance.get('/api/basedataWarehouse/treeList', {}).then(res => {
    if (res.code !== 200) {
      ElMessage.error(res.message);
      return false;
    }
    wareList.value = res.data;
  });
};

// 获取列表接口
const getList = () => {
  axiosInstance.post('/api/materialExamine/getPage', {
    ...searchParam.value,
    ...pageSearch.value,
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 重置搜索条件
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  // current.value = 1
  getList();
};

</script>
<style scoped></style>
